package com.imooc.admin.controller;

import com.imooc.admin.service.CategoryService;
import com.imooc.api.controller.admin.CategoryControllerApi;
import com.imooc.api.controller.user.BaseControllerApi;
import com.imooc.grance.result.GraceJsonResult;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.pojo.Category;
import com.imooc.pojo.bo.SaveCategoryBO;
import com.imooc.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/21/19:57
 * @Description:
 */
@RestController
public class CategoryController extends BaseControllerApi implements CategoryControllerApi {

    @Autowired
    private CategoryService categoryService;
    @Override
    public GraceJsonResult saveOrUpdateCategory(SaveCategoryBO saveCategoryBO) {

        String name = saveCategoryBO.getName();
        if (StringUtils.isBlank(name) ||"null".equalsIgnoreCase(name)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.CATEGORY_NOT_EMPTY);
        }
        Category category = new Category();
        BeanUtils.copyProperties(saveCategoryBO,category);
        boolean result = categoryService.queryIsExist(saveCategoryBO.getName());
        if (result) {
            categoryService.insertCategory(category);
        }
        categoryService.updateCategory(category);
        return GraceJsonResult.ok();
    }

    @Override
    public GraceJsonResult getCatList() {
        List<Category> categoryList = categoryService.findAll();
        return GraceJsonResult.ok(categoryList);
    }

    @Override
    public GraceJsonResult getCats() {
        //先从redis中查询，redis中没有再从mysql中查询，mysql中查询出来之后再放入redis中
        String categoryList = redis.get(REDIS_ALL_CATEGORY);
        List<Category> allCats = null;
        if (StringUtils.isBlank(categoryList)) {
            allCats = categoryService.findAllCats();
            redis.set(REDIS_ALL_CATEGORY, JsonUtils.objectToJson(allCats));
        }else {
            allCats = JsonUtils.jsonToList(categoryList, Category.class);
        }
        return GraceJsonResult.ok(allCats);
    }
}
